import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
import { Toast } from "vant";
import { getToken } from "@/utils/auth";
import { getErrMsg } from "@/utils/errMsg";
import router from "@/router/index";
const errorHandler = (error: AxiosError) => {
  console.log(error);
  const status = error?.response?.status as number;
  error.message = getErrMsg(status) || "未知错误";
  Toast(error.message);
  return Promise.reject(error);
};

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
});

interface configExtend {
  [key: string]: any;
}

//请求拦截
service.interceptors.request.use(
  (config: AxiosRequestConfig & configExtend) => {
    config.headers["Authorization"] = getToken() || null;
    if (!config.loading) {
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: ""
      });
    }
    return config;
  },
  (error) => {
    Toast.clear();
    return errorHandler(error);
  }
);

//响应拦截
service.interceptors.response.use(
  (response: AxiosResponse) => {
    Toast.clear();
    const { data } = response;
    if (data.code != 200) {
      if (data.msg) Toast.fail(data.msg);
      if (data.code == 401) {
        //未登录
        router.push("/login");
        return Promise.reject("未登录");
      }
      return Promise.reject(data.msg);
    }
    return Promise.resolve(data);
  },
  (error) => {
    Toast.clear();
    return errorHandler(error);
  }
);

const get = (url: string, config?: any) => {
  return service.get(url, config);
};
const post = (url: string, data?: any, config?: any) => {
  return service.post(url, data, config);
};

export { get, post };
